#include <batterycontroller.h>
#include <fstream>
#include <filesystem>
#include <iostream>

BatteryController::BatteryController() 
{
    findBatteryPath();
}

BatteryController::~BatteryController() 
{
    
}

void BatteryController::findBatteryPath() {
    batteryPath.clear();

    const std::string powerSupplyPath = "/sys/class/power_supply/";

    std::error_code ec;
    for (const auto &entry : std::filesystem::directory_iterator(powerSupplyPath, ec)) {
        if (ec) {
            std::cerr << "Failed to iterate power supply directory: " << ec.message() << std::endl;
            break;
        }

        if (entry.is_directory(ec)) {
            std::string bat = entry.path().filename();
            if (bat.find("BAT") != std::string::npos) {
                batteryPath = bat;
                break;
            }
        }
    }
}

int BatteryController::getBatteryLevel()
{
    if (batteryPath.empty()) {
        return -1;
    }

    const std::string capacityFilePath = "/sys/class/power_supply/" + batteryPath + "/capacity";
    std::ifstream batteryFile(capacityFilePath);
    
    if (!batteryFile.is_open()) {
        return -1;
    }

    int level = -1;
    batteryFile >> level;
    
    return level;
}

BatteryController::BatteryStatus BatteryController::getBatteryStatus()
{
    if (batteryPath.empty())
    {
        findBatteryPath();
    }

    std::ifstream batteryFile("/sys/class/power_supply/" + batteryPath + "/status");
    if (batteryFile.is_open())
    {
        std::string status;
        batteryFile >> status;
        if (status == "Charging")
        {
            return BatteryStatus::Charging;
        }
        else if (status == "Discharging")
        {
            return BatteryStatus::Discharging;
        }
        else if (status == "Full")
        {
            return BatteryStatus::Full;
        }
        else
        {
            return BatteryStatus::Unknown;

        }
    }
    return BatteryStatus();
}
